#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'arrow'
__explain__ = ''

import os

from django.conf import settings

from AvCarrier.celery import app
from av_editor.models import MaterialFile, DOWNLOAD_SUCCESS, DOWNLOADING, DOWNLOAD_FAIL
from av_manager.models import PlatForm, CarriedContent
from common.constants import VIDEO_TYPE
from common.file_utils import custom_file_path


@app.task(bind=True, time_limit=12 * 3600)
def carry_video(self, plat_id, carry_content_id, video_id, video_name, suffix='mp4'):
    plat = PlatForm.objects.get(id=plat_id)
    manager = plat.get_manager()
    carry_content = CarriedContent.objects.get(id=carry_content_id)
    file_name = f"{carry_content.channel.name}"
    # 文件应保存的相对地址
    relative_path = custom_file_path(plat.code.lower(), file_name)
    # 下载文件用，文件绝对地址
    file_path = settings.MEDIA_ROOT + "/" + relative_path
    file_instance = MaterialFile.objects.create(file=None, file_type=VIDEO_TYPE, name=file_name, source=plat.code,
                                                status=DOWNLOADING, note=video_name)
    res = manager.download_video(video_id=video_id, file_name=file_path, suffix=suffix)
    file_name = res.get("file_name")
    suffix = res.get("suffix")
    # 绝对位置（with 最终文件名）
    final_name_with_path = f"{file_name}.{suffix}"
    # 最终文件名
    final_name = final_name_with_path.rsplit("/", maxsplit=1)[1]
    # 最终文件名，保存到file字段的相对地址
    save_file_path = relative_path.rsplit("/", maxsplit=1)[0] + "/" + final_name
    if os.path.exists(final_name_with_path):
        file_instance.name = final_name
        file_instance.file = save_file_path
        file_instance.suffix = suffix
        file_instance.status = DOWNLOAD_SUCCESS
    else:
        file_instance.status = DOWNLOAD_FAIL
    file_instance.save()

    carry_content.material = file_instance
    carry_content.save()
